package uni.call.app;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.ParseException;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.PendingIntent;
import android.app.TabActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.WindowManager;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;
import android.net.sip.*;

public class HomeActivity extends TabActivity
{
	public static String Registered = "false";
	public static IncomingCallReceiver CallReceiver;
    
    public static SipManager SipManager = null;
    public static SipProfile MySipProfile = null;

    private static final int Create_New_Account =1;
    private static final int UPDATE_SETTINGS_DIALOG = 2;
    
	public void onCreate(Bundle savedInstanceState)
	{
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.tab_host);
	    
	    ConnectivityManager manager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
	    Boolean isWifi = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting();
	    
	    if(!isWifi)
	    {
            AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
            alertbox.setMessage(getString(R.string.NoWiFiMessage));
            alertbox.setTitle(getString(R.string.NoWiFiTitle));
            alertbox.setPositiveButton(getString(android.R.string.ok), new DialogInterface.OnClickListener()
            {
                public void onClick(DialogInterface arg0, int arg1) 
                {
                	startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
                }
            });
 
            alertbox.setNegativeButton(getString(android.R.string.no), new DialogInterface.OnClickListener() 
            {
                public void onClick(DialogInterface arg0, int arg1) 
                {
                }
            });
            alertbox.show();
	    }
	    
	    Resources res = getResources(); // Resource object to get Drawables
	    TabHost tabHost = getTabHost();  // The activity TabHost
	    tabHost.setup();
	    TabHost.TabSpec spec;  // Resusable TabSpec for each tab
	    Intent intent;  // Reusable Intent for each tab

	    // Create an Intent to launch an Activity for the tab (to be reused)
	    intent = new Intent().setClass(this, DailerActivity.class);
	    intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
	    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
	    
	    // Initialize a TabSpec for each tab and add it to the TabHost
	    //String Dailer_Tab_Name = getString(R.string.Dailer_Tab);
	    spec = tabHost.newTabSpec("dailer").setIndicator("",
                      res.getDrawable(R.drawable.tab_dial_xml))
                  .setContent(intent);
	    tabHost.addTab(spec);

	    // Do the same for the other tabs
	    //String History_Tab_Name = getString(R.string.History_Tab);
	    intent = new Intent(Intent.ACTION_VIEW).setClass(this, LogActivity.class);
	    intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
	    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
	    spec = tabHost.newTabSpec("history").setIndicator("",
                      res.getDrawable(R.drawable.tab_log_xml))
                  .setContent(intent);
    	tabHost.addTab(spec);

    	//String Contacts_Tab_Name = getString(R.string.Contacts_Tab);
    	intent = new Intent().setClass(this, ContactsActivity.class);
	    intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
	    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    	spec = tabHost.newTabSpec("contacts").setIndicator("",
                      res.getDrawable(R.drawable.tab_contacts_xml))
                  .setContent(intent);
    	tabHost.addTab(spec);
    	
    	//String More_Tab_Name = getString(R.string.More_Tab);
    	intent = new Intent().setClass(this, MoreActivity.class);
	    intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
	    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    	spec = tabHost.newTabSpec("more").setIndicator("",
                      res.getDrawable(R.drawable.tab_more_xml))
                  .setContent(intent);
    	tabHost.addTab(spec);
    	
    	tabHost.setCurrentTab(0);
    
    	// Set up the intent filter.  This will be used to fire an
    	// IncomingCallReceiver when someone calls the SIP address used by this
    	// application.
    
    	IntentFilter filter = new IntentFilter();
    	filter.addAction("UniCall.app.INCOMING_CALL");
    	CallReceiver = new IncomingCallReceiver();
    	this.registerReceiver(CallReceiver, filter);
       
    	// "Push to talk" can be a serious pain when the screen keeps turning off.
    	// Let's prevent that.
    	getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    	
    	InitializeManager();
    	
    	
	}
	
    public void InitializeLocalProfile() 
    {
        if (SipManager == null) 
        {
            return;
        }
        
        if (MySipProfile != null)
        {
            CloseLocalProfile();
        }

        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
        String username = prefs.getString("namePref", "");
        String domain = prefs.getString("domainPref", "");
        String password = prefs.getString("passPref", "");

        if (username.length() == 0 || domain.length() == 0 || password.length() == 0) 
        {
        	showDialog(Create_New_Account);
        	return;
        }

        try 
        {
            SipProfile.Builder builder = new SipProfile.Builder(username, domain);
            builder.setPassword(password);
            builder.setSendKeepAlive(true);
            MySipProfile = builder.build();

            Intent i = new Intent();
            i.setAction("UniCall.app.INCOMING_CALL");
            PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, Intent.FILL_IN_DATA);
            SipManager.open(MySipProfile, pi, null);
            

            // This listener must be added AFTER manager.open is called,
            // Otherwise the methods aren't guaranteed to fire.

            SipManager.setRegistrationListener(MySipProfile.getUriString(), new SipRegistrationListener()
            {
                    public void onRegistering(String localProfileUri)
                    {
                    	UpdateStatus(getString(R.string.Registering),"");
                    }

                    public void onRegistrationDone(String localProfileUri, long expiryTime)
                    {
                    	Registered = "true";
                    	SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
                        String domain = prefs.getString("domainPref", "");
                        if(domain.equals("sip.vectrafon.com"))
                        {
                        	GetBalance();
                        	UpdateStatus(getString(R.string.Registered),getString(R.string.Balance)+SAXHandle.Balance);
                        }
                        else
                        {
                        	UpdateStatus(getString(R.string.Registered),"");	
                        }
                    	
                    }
                    public void onRegistrationFailed(String localProfileUri, int errorCode, String errorMessage)
                    {
                    	UpdateStatus(getString(R.string.Failed),"");
                    }
                });
        }
        catch (ParseException pe)
        {
        	UpdateStatus(getString(R.string.ConnectionError),"");
        }
        catch (SipException se)
        {
        	UpdateStatus(getString(R.string.ConnectionError),"");
        }
        
    }
    
   
    @Override
    protected Dialog onCreateDialog(int id)
    {
        switch (id)
        {
            case UPDATE_SETTINGS_DIALOG:
                return new AlertDialog.Builder(this)
                        .setMessage(getString(R.string.PleaseEditSip))
                        .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener()
                        {
                            public void onClick(DialogInterface dialog, int whichButton)
                            {
                            	UpdatePreferences();
                            }
                        })
                        .setNegativeButton(
                                android.R.string.cancel, new DialogInterface.OnClickListener()
                                {
                                    public void onClick(DialogInterface dialog, int whichButton)
                                    {
                                    }
                        })
                        .create();
            
            case Create_New_Account:
            	return new AlertDialog.Builder(this)
                .setMessage(getString(R.string.Acount_Title))
                .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener()
                {
                    public void onClick(DialogInterface dialog, int whichButton)
                    {
                    	CreateAccount();
                    	showDialog(UPDATE_SETTINGS_DIALOG);
                    }
                })
                .setNegativeButton(
                        android.R.string.cancel, new DialogInterface.OnClickListener()
                        {
                            public void onClick(DialogInterface dialog, int whichButton)
                            {
                            	showDialog(UPDATE_SETTINGS_DIALOG);
                            }
                })
                .create();
        }
        return null;
    }
   
    //Add Item To Menu
    public boolean onCreateOptionsMenu(Menu menu)
    {
        menu.add(0, UPDATE_SETTINGS_DIALOG , 0, getString(R.string.EditSip ));
        return true;
    }
    
    //On Item Selected Go TO Preferences
    public boolean onOptionsItemSelected(MenuItem item)
    {
        switch (item.getItemId())
        {
            case UPDATE_SETTINGS_DIALOG:
            	UpdatePreferences();
                break;
        }
        return true;
    }
    
    //Go Preferneces
    public void UpdatePreferences()
    {
    	Intent settingsActivity = new Intent(getBaseContext(), SipSettings.class);
        //startActivity(settingsActivity);
        startActivityForResult(settingsActivity, 1);
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
	     super.onActivityResult(requestCode, resultCode, data);
	     if(requestCode==1)
	     {
	    	InitializeManager();
	     }
    }
    
    //Go To Website
    public void CreateAccount()
    {
		Uri uri = Uri.parse( "http://aspspider.info/unicall/Registration.aspx" );
		startActivity( new Intent( Intent.ACTION_VIEW, uri ));
    }
    
    //Get Balance
    public void GetBalance()
    {
    	URL url;
       
		try {
			url = new URL(
			"https://gateway1.vectrafon.com/A2BCustomer_UI/vectrafon/API.php?username=962799146899&password=082929129037&request=info");
			
	    	/* Get a SAXParser from the SAXPArserFactory. */
	    	SAXParserFactory spf = SAXParserFactory.newInstance();
	    	SAXParser sp = spf.newSAXParser();

	    	/* Get the XMLReader of the SAXParser we created. */
	    	XMLReader xr = sp.getXMLReader();
	    	/* Create a new ContentHandler and apply it to the XML-Reader*/
	    	SAXHandle myExampleHandler = new SAXHandle();
	    	xr.setContentHandler(myExampleHandler);


	    	/* Parse the xml-data from our URL. */
	    	xr.parse(new InputSource(url.openStream()));
	    	
	    	/* Parsing has finished. */
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    } 
    
    /**
     * Closes out your local profile, freeing associated objects into memory
     * and unregistering your device from the server.
     */
    public void CloseLocalProfile()
    {
        if (SipManager == null) 
        {
            return;
        }
        try 
        {
            if (MySipProfile != null) 
            {
                SipManager.close(MySipProfile.getUriString());
            }
        } 
        catch (Exception ee) 
       {
            Log.d("WalkieTalkieActivity/onDestroy", "Failed to close local profile.", ee);
        }
    }
   
    public void UpdateStatus(final String RegStatus, final String MyBalance)
    {
        // Be a good citizen.  Make sure UI changes fire on the UI thread.
        this.runOnUiThread(new Runnable()
        {
            public void run()
            {
            	TextView StatusTV;
            	TextView BalanceTV;
                BalanceTV =  (TextView)findViewById(R.id.Balance);
                StatusTV = (TextView) findViewById(R.id.Status);
            	StatusTV.setText(RegStatus);
            	BalanceTV.setText(MyBalance);
            }             
        });
    }
  
	@Override
    public void onDestroy()
    {
        super.onDestroy();
        if (OutGoingCall.OutgoingCall != null)
        {
        	OutGoingCall.OutgoingCall.close();
        }
        if (IncomingCallReceiver.IncomingCall != null)
        {
        	IncomingCallReceiver.IncomingCall.close();
        }
        CloseLocalProfile();

        if (CallReceiver != null)
        {
            this.unregisterReceiver(CallReceiver);
        }
    }

    public void InitializeManager()
    {
        if(SipManager == null)
        {
          SipManager = SipManager.newInstance(this);
        }
        InitializeLocalProfile();
    }
}
